package com.tianlu.store.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.tianlu.store.common.ResultCode;
import com.tianlu.store.common.ServiceException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class ServletsUtils extends ServletUtil {
    public ServletsUtils() {
    }

    public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
        response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000L);
        response.setHeader("Cache-Control", "private, max-age=" + expiresSeconds);
    }

    public static void setNoCacheHeader(HttpServletResponse response) {
        response.setDateHeader("Expires", 1L);
        response.addHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
    }

    public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
        response.setDateHeader("Last-Modified", lastModifiedDate);
    }

    public static void setEtag(HttpServletResponse response, String etag) {
        response.setHeader("ETag", etag);
    }

    public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
        String headerValue = request.getHeader("If-None-Match");
        if (headerValue != null) {
            boolean conditionSatisfied = false;
            if (!"*".equals(headerValue)) {
                StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

                while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                    String currentToken = commaTokenizer.nextToken();
                    if (currentToken.trim().equals(etag)) {
                        conditionSatisfied = true;
                    }
                }
            } else {
                conditionSatisfied = true;
            }

            if (conditionSatisfied) {
                response.setStatus(304);
                response.setHeader("ETag", etag);
                return false;
            }
        }

        return true;
    }

    public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
        try {
            String encodedFileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        } catch (UnsupportedEncodingException var3) {
            var3.printStackTrace();
        }

    }

    public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        Map<String, Object> params = new TreeMap();
        if (request == null) {
            return params;
        } else {
            Enumeration paramNames = request.getParameterNames();
            String pre = prefix;
            if (prefix == null) {
                pre = "";
            }

            while (paramNames != null && paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if ("".equals(pre) || paramName.startsWith(pre)) {
                    String unPrefixed = paramName.substring(pre.length());
                    String[] values = request.getParameterValues(paramName);
                    if (values != null && values.length != 0) {
                        params.put(unPrefixed, values[0]);
                    } else {
                        params.put(unPrefixed, values);
                    }
                }
            }

            return params;
        }
    }

    public static String encodeParameterStringWithPrefix(Map<String, Object> params, String prefix) {
        StringBuilder queryStringBuilder = new StringBuilder();
        String pre = prefix;
        if (prefix == null) {
            pre = "";
        }

        Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry) it.next();
            queryStringBuilder.append(pre).append((String) entry.getKey()).append("=").append(entry.getValue());
            if (it.hasNext()) {
                queryStringBuilder.append("&");
            }
        }

        return queryStringBuilder.toString();
    }

    public static String encodeHttpBasic(String userName, String password) {
        String encode = userName + ":" + password;
        return "Basic " + Arrays.toString(Base64.getEncoder().encode(encode.getBytes()));
    }

    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (Exception var1) {
            return null;
        }
    }

    public static String getPlatform() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        } else {
            return request.getHeader("PLATFORM_") == null ? "" : request.getHeader("PLATFORM_");
        }
    }

    public static String getPlatformCode() {
        HttpServletRequest request = getRequest();
        return request == null ? null : request.getHeader("PlatformCode");
    }

    public static String getToken(boolean flag) {
        HttpServletRequest request = getRequest();
        if (request != null && !StrUtil.isEmpty(request.getHeader("Token"))) {
            return request.getHeader("Token");
        } else if (flag) {
            return null;
        } else {
            throw new ServiceException(ResultCode.CODE_401);
        }
    }

    public static String getRemoteAddress() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        } else {
            String remoteAddress = request.getHeader("X-Real-IP");
            if (StrUtil.isEmpty(remoteAddress)) {
                remoteAddress = request.getHeader("X-Forwarded-For");
            } else if (StrUtil.isEmpty(remoteAddress)) {
                remoteAddress = request.getHeader("Proxy-Client-IP");
            } else if (StrUtil.isEmpty(remoteAddress)) {
                remoteAddress = request.getHeader("WL-Proxy-Client-IP");
            }

            return remoteAddress != null ? remoteAddress : request.getRemoteAddr();
        }
    }
}

